C# Linq item index

95

C# Linq item index -

// C# program to find the index value of
// the even numbers using LINQ
using System;
using System.Collections.Generic;
using System.Linq;
  
class GfG{
      
static void Main(string[] args)
{
      
    // Creating a list of integer type
    List<int> data = new List<int>();
      
    // Add elements to the list
    data.Add(2);
    data.Add(3);
    data.Add(4);
    data.Add(5);
    data.Add(6);
    data.Add(12);
    data.Add(11);
  
    // Get the index of numbers
    var indexdata = data.Select((val, indexvalue) => new
                    { 
                        Data = val, 
                        IndexPosition = indexvalue
                    }).Where(n => n.Data % 2 == 0).Select(
                    result => new 
                    { 
                        Number = result.Data,
                        IndexPosition = result.IndexPosition 
                    });
                      
    // Display the index and numbers
    // of the even numbers from the array
    foreach(var i in indexdata)
    {
        Console.WriteLine("Index Value:" + i.IndexPosition + 
                          " - Even Number: " + i.Number);
    }
}
}

Comments

Submit
0 Comments